<template>
  <span v-if="renderType === 'renderCell'">{{innerValue}}</span>
  <z-dict-select-tag
    v-else
    :value="value"
    v-bind="cellProps"
    :options="options"
    :triggerChange="true"
    :getPopupContainer="getPopupContainer"
    @change="handleSelectChange"
  />
</template>

<script>
import ZDictSelectTag from '@/components/dict/ZDictSelectTag'
import { initDictOptions, filterDictText } from '@/components/dict/ZDictSelectUtil'
import { isArray, isObject } from 'lodash'
export default {
  name: 'VxeSelectCell',
  components: {
    ZDictSelectTag
  },
  props: {
    value: [String, Number],
    params: Object,
    renderOptions: Object,
    cellProps: Object,
    renderType: String
  },
  data() {
    return {
      options: [],
      loading: false,
      innerValue: ''
    }
  },
  watch: {
    value() {
      this.getInnerValue()
    }
  },
  methods: {
    getInnerValue() {
      this.innerValue = this.value ? filterDictText(this.options, this.value) : ''
    },
    handleSelectChange(val) {
      const { row, column, $table } = this.params
      this.$set(row, column.property, val)
      $table.updateStatus(this.params)
    },
    initDictData() { // 获取字典数据
      const { column } = this.params
      if (column.own && column.own.loading) { // 当前列已有单元格发起请求，不重复请求
        return column.own.loading
      }
      if (column.own && column.own.options) { // 当前列已有options数据，不重复请求
        return new Promise((resolve, reject) => {
          resolve({ ...column.own.options })
        })
      }
      if (this.cellProps.options) {
        return new Promise((resolve, reject) => {
          resolve([...this.cellProps.options])
        })
      }
      const loading = new Promise((resolve, reject) => {
        // 根据字典Code, 初始化字典数组
        initDictOptions(this.cellProps.dictCode).then(res => {
          if (res.success && res.result) {
            this.$set(column, 'own', { // 把options放到column上避免每行都请求数据
              options: res.result,
              loading: false
            })
            resolve(res.result)
          }
        })
      })
      this.$set(column, 'own', { loading: loading })
      return loading
    },
    init() {
      this.initDictData().then(res => {
        if (isObject(res)) {
          this.options = []
          res.items.forEach(item => {
            this.options.push({
              label: item.itemText,
              value: item.itemValue
            })
          })
          if (!this.value && this.cellProps.defaultValue) this.handleSelectChange(res.dictDefaultValue)
        } else if (isArray(res)) {
          this.options = res
        }
        this.getInnerValue()
      })
    },
    getPopupContainer() {
      return document.body
    }
  },
  created() {
    this.init()
  },
  enhanced: {
    translate: true
  }
}
</script>
